const fs = require('fs');
const path = require('path');

// 读取配置文件
const config = JSON.parse(fs.readFileSync('./config.json', 'utf8'));

// 质量验证规则
const validationRules = {
  // SVG文件完整性检查
  svgIntegrity: {
    requiredTags: ['svg', 'defs', 'g'],
    requiredAttributes: ['width', 'height', 'viewBox'],
    maxFileSize: 500 * 1024, // 500KB
    minFileSize: 1024 // 1KB
  },
  
  // 样式一致性检查
  styleConsistency: {
    allowedColors: [
      '#2563EB', '#64748B', '#F59E0B', '#F8FAFC', 
      '#FFFFFF', '#1E293B', '#E2E8F0', '#10B981', '#EF4444',
      '#3B82F6', '#6366F1', '#8B5CF6', '#A855F7', '#D946EF',
      '#EC4899', '#F43F5E', '#EF4444', '#F97316', '#F59E0B',
      '#EAB308', '#84CC16', '#22C55E', '#10B981', '#14B8A6',
      '#06B6D4', '#0EA5E9', '#3B82F6', '#6366F1', '#8B5CF6',
      '#000000', '#374151', '#6B7280', '#9CA3AF', '#D1D5DB',
      '#F3F4F6', '#F9FAFB'
    ],
    allowedFonts: ['Inter', 'system-ui', 'sans-serif', 'Arial', 'Helvetica', 'Roboto', 'Open Sans'],
    allowedBorderRadius: ['0', '2', '4', '6', '8', '10', '12', '14', '16', '20', '24']
  },
  
  // 文件命名规范
  namingConvention: {
    pattern: /^HRC[A-Z][a-zA-Z]*Screen\.svg$/,
    requiredPrefix: 'HRC',
    requiredSuffix: 'Screen.svg'
  }
};

// 验证SVG文件完整性
function validateSVGIntegrity(filePath) {
  const issues = [];
  
  try {
    const stats = fs.statSync(filePath);
    const content = fs.readFileSync(filePath, 'utf8');
    
    // 检查文件大小
    if (stats.size > validationRules.svgIntegrity.maxFileSize) {
      issues.push(`文件过大: ${(stats.size / 1024).toFixed(2)}KB > ${validationRules.svgIntegrity.maxFileSize / 1024}KB`);
    }
    
    if (stats.size < validationRules.svgIntegrity.minFileSize) {
      issues.push(`文件过小: ${stats.size}B < ${validationRules.svgIntegrity.minFileSize}B`);
    }
    
    // 检查必需的标签
    validationRules.svgIntegrity.requiredTags.forEach(tag => {
      if (!content.includes(`<${tag}`)) {
        issues.push(`缺少必需标签: <${tag}>`);
      }
    });
    
    // 检查必需的属性
    validationRules.svgIntegrity.requiredAttributes.forEach(attr => {
      if (!content.includes(`${attr}="`)) {
        issues.push(`缺少必需属性: ${attr}`);
      }
    });
    
    // 检查XML格式
    if (!content.trim().startsWith('<?xml') && !content.trim().startsWith('<svg')) {
      issues.push('不是有效的SVG格式');
    }
    
  } catch (error) {
    issues.push(`文件读取错误: ${error.message}`);
  }
  
  return issues;
}

// 验证样式一致性
function validateStyleConsistency(filePath) {
  const issues = [];
  
  try {
    const content = fs.readFileSync(filePath, 'utf8');
    
    // 检查颜色使用
    const colorRegex = /#[0-9A-Fa-f]{6}/g;
    const colors = content.match(colorRegex) || [];
    const uniqueColors = [...new Set(colors)];
    
    uniqueColors.forEach(color => {
      if (!validationRules.styleConsistency.allowedColors.includes(color.toUpperCase())) {
        issues.push(`使用了未授权的颜色: ${color}`);
      }
    });
    
    // 检查字体使用
    const fontRegex = /font-family="([^"]+)"/g;
    let fontMatch;
    while ((fontMatch = fontRegex.exec(content)) !== null) {
      const font = fontMatch[1];
      if (!validationRules.styleConsistency.allowedFonts.some(allowedFont => font.includes(allowedFont))) {
        issues.push(`使用了未授权的字体: ${font}`);
      }
    }
    
    // 检查圆角使用
    const radiusRegex = /r[xy]="(\d+)"/g;
    let radiusMatch;
    while ((radiusMatch = radiusRegex.exec(content)) !== null) {
      const radius = radiusMatch[1];
      if (!validationRules.styleConsistency.allowedBorderRadius.includes(radius)) {
        issues.push(`使用了未授权的圆角值: ${radius}`);
      }
    }
    
  } catch (error) {
    issues.push(`样式检查错误: ${error.message}`);
  }
  
  return issues;
}

// 验证文件命名规范
function validateNamingConvention(filename) {
  const issues = [];
  
  if (!validationRules.namingConvention.pattern.test(filename)) {
    issues.push(`文件名不符合命名规范: ${filename}`);
  }
  
  if (!filename.startsWith(validationRules.namingConvention.requiredPrefix)) {
    issues.push(`文件名缺少必需前缀: ${validationRules.namingConvention.requiredPrefix}`);
  }
  
  if (!filename.endsWith(validationRules.namingConvention.requiredSuffix)) {
    issues.push(`文件名缺少必需后缀: ${validationRules.namingConvention.requiredSuffix}`);
  }
  
  return issues;
}

// 验证单个文件
function validateFile(filePath) {
  const filename = path.basename(filePath);
  const result = {
    filename,
    filePath,
    passed: true,
    issues: [],
    checks: {
      integrity: [],
      styleConsistency: [],
      namingConvention: []
    }
  };
  
  // 执行各项检查
  result.checks.integrity = validateSVGIntegrity(filePath);
  result.checks.styleConsistency = validateStyleConsistency(filePath);
  result.checks.namingConvention = validateNamingConvention(filename);
  
  // 汇总所有问题
  result.issues = [
    ...result.checks.integrity,
    ...result.checks.styleConsistency,
    ...result.checks.namingConvention
  ];
  
  result.passed = result.issues.length === 0;
  
  return result;
}

// 批量验证文件
function batchValidate() {
  try {
    console.log('开始质量验证...');
    
    const updatedDir = path.join(config.paths.workingDir, 'updated-prototypes');
    
    if (!fs.existsSync(updatedDir)) {
      throw new Error(`更新后的原型目录不存在: ${updatedDir}`);
    }
    
    // 获取所有SVG文件
    const svgFiles = fs.readdirSync(updatedDir)
      .filter(file => file.endsWith('.svg'))
      .map(file => path.join(updatedDir, file));
    
    console.log(`找到 ${svgFiles.length} 个SVG文件进行验证`);
    
    const results = [];
    let passedFiles = 0;
    let totalIssues = 0;
    
    // 验证每个文件
    svgFiles.forEach(filePath => {
      const result = validateFile(filePath);
      results.push(result);
      
      if (result.passed) {
        passedFiles++;
        console.log(`✓ ${result.filename} - 通过验证`);
      } else {
        totalIssues += result.issues.length;
        console.log(`✗ ${result.filename} - 发现 ${result.issues.length} 个问题`);
        result.issues.forEach(issue => {
          console.log(`    - ${issue}`);
        });
      }
    });
    
    // 生成验证报告
    const report = {
      timestamp: new Date().toISOString(),
      summary: {
        totalFiles: svgFiles.length,
        passedFiles,
        failedFiles: svgFiles.length - passedFiles,
        totalIssues,
        passRate: ((passedFiles / svgFiles.length) * 100).toFixed(2) + '%'
      },
      validationRules,
      results
    };
    
    // 保存报告
    fs.writeFileSync('./validation/quality-validation-report.json', JSON.stringify(report, null, 2));
    
    // 生成可读报告
    const readableReport = generateValidationReport(report);
    fs.writeFileSync('./validation/quality-validation-summary.md', readableReport);
    
    console.log('\n质量验证完成!');
    console.log(`- 总文件数: ${svgFiles.length}`);
    console.log(`- 通过验证: ${passedFiles}`);
    console.log(`- 验证失败: ${svgFiles.length - passedFiles}`);
    console.log(`- 总问题数: ${totalIssues}`);
    console.log(`- 通过率: ${report.summary.passRate}`);
    
    return report;
    
  } catch (error) {
    console.error('质量验证失败:', error.message);
    throw error;
  }
}

// 生成验证报告
function generateValidationReport(report) {
  const { summary, results } = report;
  
  let markdown = `# 质量验证报告\n\n`;
  markdown += `执行时间: ${report.timestamp}\n\n`;
  
  markdown += `## 验证概要\n\n`;
  markdown += `- 总文件数: ${summary.totalFiles}\n`;
  markdown += `- 通过验证: ${summary.passedFiles}\n`;
  markdown += `- 验证失败: ${summary.failedFiles}\n`;
  markdown += `- 总问题数: ${summary.totalIssues}\n`;
  markdown += `- 通过率: ${summary.passRate}\n\n`;
  
  // 验证规则说明
  markdown += `## 验证规则\n\n`;
  markdown += `### SVG完整性检查\n`;
  markdown += `- 必需标签: ${validationRules.svgIntegrity.requiredTags.join(', ')}\n`;
  markdown += `- 必需属性: ${validationRules.svgIntegrity.requiredAttributes.join(', ')}\n`;
  markdown += `- 文件大小: ${validationRules.svgIntegrity.minFileSize}B - ${validationRules.svgIntegrity.maxFileSize / 1024}KB\n\n`;
  
  markdown += `### 样式一致性检查\n`;
  markdown += `- 允许的颜色: ${validationRules.styleConsistency.allowedColors.join(', ')}\n`;
  markdown += `- 允许的字体: ${validationRules.styleConsistency.allowedFonts.join(', ')}\n`;
  markdown += `- 允许的圆角: ${validationRules.styleConsistency.allowedBorderRadius.join(', ')}\n\n`;
  
  markdown += `### 命名规范检查\n`;
  markdown += `- 命名模式: ${validationRules.namingConvention.pattern}\n`;
  markdown += `- 必需前缀: ${validationRules.namingConvention.requiredPrefix}\n`;
  markdown += `- 必需后缀: ${validationRules.namingConvention.requiredSuffix}\n\n`;
  
  // 详细结果
  const passedFiles = results.filter(r => r.passed);
  const failedFiles = results.filter(r => !r.passed);
  
  if (passedFiles.length > 0) {
    markdown += `## 通过验证的文件 (${passedFiles.length})\n\n`;
    passedFiles.forEach(file => {
      markdown += `- ✓ ${file.filename}\n`;
    });
    markdown += `\n`;
  }
  
  if (failedFiles.length > 0) {
    markdown += `## 验证失败的文件 (${failedFiles.length})\n\n`;
    failedFiles.forEach(file => {
      markdown += `### ✗ ${file.filename}\n`;
      markdown += `问题数量: ${file.issues.length}\n\n`;
      
      if (file.checks.integrity.length > 0) {
        markdown += `**完整性问题:**\n`;
        file.checks.integrity.forEach(issue => {
          markdown += `- ${issue}\n`;
        });
        markdown += `\n`;
      }
      
      if (file.checks.styleConsistency.length > 0) {
        markdown += `**样式一致性问题:**\n`;
        file.checks.styleConsistency.forEach(issue => {
          markdown += `- ${issue}\n`;
        });
        markdown += `\n`;
      }
      
      if (file.checks.namingConvention.length > 0) {
        markdown += `**命名规范问题:**\n`;
        file.checks.namingConvention.forEach(issue => {
          markdown += `- ${issue}\n`;
        });
        markdown += `\n`;
      }
    });
  }
  
  return markdown;
}

// 主执行函数
function main() {
  try {
    const report = batchValidate();
    console.log('\n✓ 质量验证任务完成');
    console.log('✓ 验证报告已生成: quality-validation-report.json');
    console.log('✓ 可读报告已生成: quality-validation-summary.md');
    
    if (report.summary.failedFiles > 0) {
      console.log('\n⚠️  发现质量问题，请查看验证报告进行修复');
    } else {
      console.log('\n🎉 所有文件都通过了质量验证!');
    }
  } catch (error) {
    console.error('质量验证失败:', error.message);
    process.exit(1);
  }
}

if (require.main === module) {
  main();
}

module.exports = { validateFile, batchValidate, validationRules };